// 2025/10/25
// 课程表二

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> prev_cnt(numCourses, 0);
        vector<vector<int>> afters(numCourses);
        for(auto& limit : prerequisites)
        {
            prev_cnt[limit[0]]++;
            afters[limit[1]].emplace_back(limit[0]);
        }

        queue<int> ready;
        for(int i = 0; i < numCourses; i++)
        {
            if(prev_cnt[i] == 0)
            {
                ready.emplace(i);
            }
        }

        vector<int> ans;
        while(!ready.empty())
        {
            int next = ready.front();
            ready.pop();
            ans.emplace_back(next);
            for(auto& after : afters[next])
            {
                if(--prev_cnt[after] == 0)
                {
                    ready.emplace(after);
                }
            }
        }
        if(ans.size() == numCourses)
            return ans;
        else
            return vector<int>();
    }
};